import React, { useEffect, useMemo, useState } from "react"
import { Picker, View, Text } from "@tarojs/components"
import Page from "@/components/page"
import PageNav from "@/components/pageNav"
import moment from "moment"
import { MoneyFormat } from "@/utils/format"
import account from "@/store/account"
import http from "@/request"
import { HideLoading, ShowLoading, ShowToast } from "@/utils"
import MemberPie from "./memberPie"

import "./index.scss"
import EditBalance from "./editBalance"

interface monthDataType {
    balance: number,
    expense: number,
    income: number,
    month: string
}
const Balance: React.FC = () => {
    const [total, setTotal] = useState(0)
    const [year, setYear] = useState(moment().year())
    const years = [moment().year(), moment().year() - 1, moment().year() - 2]
    const [monthData, setMonthData] = useState<monthDataType[]>([])
    const [yearData, setYearData] = useState<{
        income: number,
        expense: number
    }>({
        income: 0,
        expense: 0
    })
    const [membersData, setMembersData] = useState([])
    const [editVisible, setEditVisible] = useState(false)

    const months = useMemo(() => {
        let mon = 12
        if (year === moment().year()) {
            mon = moment().month() + 1
        }
        return new Array(mon).fill('').map((_, index) => {
            const num = mon - index
            const month = `${year}-${num > 9 ? num : '0' + num}`
            return {
                name: `${num}月`,
                id: num,
                month,
                data: monthData.find(item => item.month === month) || {
                    balance: 0,
                    expense: 0,
                    income: 0,
                    month
                }
            }
        })

    }, [year, monthData])

    const yearsChange = (e) => {
        setYear(years[e.target.value])
    }
    const queryData = () => {
        const startDate = `${year}-01-01`
        ShowLoading()
        const params = {
            startDate,
            endDate: moment(startDate).endOf('year').format('YYYY-MM-DD'),
            accountId: account.activeAccount?.id
        }
        http.post('/bills/statistics/month', params).then(res => {
            const resData = res.data || []
            setMonthData(resData)
            setYearData(resData.reduce((sum, cur) => {
                return {
                    income: sum.income + cur.income,
                    expense: sum.expense + cur.expense
                }
            }, {
                income: 0,
                expense: 0
            }));

            HideLoading()
        }).catch(err => {
            ShowToast(err.msg || '获取统计数据失败')
        })
    }

    const queryPieData = () => {
        // 为了避免总金额只统计到了当年了，这儿写死2024，后面逻辑完善后再修改
        const startDate = `${2024}-01-01`
        http.post('/bills/statistics/member', {
            accountId: account.activeAccount?.id,
            endDate: moment().format('YYYY-MM-DD'),
            startDate 
        }).then(res => {
            setMembersData(res.data || [])
        })
    }

    const editClose = (isSure) => {
        setEditVisible(false)
        if (isSure) {
            queryPieData()
        }
    }

    useEffect(() => {
        queryData()
        queryPieData()
    }, [year])

    return (
        <Page className="balance-page flex-column flex-item card-background">
            <PageNav showBack className="page-header need-filter">
                <View className="picker-name flex-row flex-item">
                    <Text>统计年份：</Text>
                    <Picker mode='selector' range={years} onChange={yearsChange}>
                        <View className='picker'>
                            <Text>{year}</Text>
                            <Text className="iconfont icon-base-down"></Text>
                        </View>
                    </Picker>
                </View>
            </PageNav>
            <View className="page-body need-filter flex-column flex-item flex1">
                <View className="balance-info-card page-background text-main-color">
                    <View className="info-item font-size24">账本结余</View>
                    <View className="flex-row flex-item">
                        <View className="balance-val flex1">{MoneyFormat(total)}</View>
                        <View onClick={() => setEditVisible(true)} className="balance-val iconfont icon-bianji"></View>
                    </View>
                    <MemberPie pieData={membersData} hide={editVisible} onInit={setTotal}></MemberPie>
                    <View className="flex-row font-size24">
                        <View className="info-item flex1">
                            <View className="info-label">年度收入</View>
                            <View className="income-val font-size28">{MoneyFormat(yearData.income)}</View>
                        </View>
                        <View className="info-item flex1">
                            <View className="info-label">年度支出</View>
                            <View className="income-val font-size28">{MoneyFormat(yearData.expense)}</View>
                        </View>
                        <View className="info-item">
                            <View className="info-label">年度结余</View>
                            <View className="income-val font-size28">{MoneyFormat(yearData.income - yearData.expense)}</View>
                        </View>
                    </View>
                </View>
                <View className="month-table text-main-color">
                    <View className="table-header font-size24">
                        <View className="table-row flex-row">
                            <View className="column-name month-column">月份</View>
                            <View className="column-name flex1">收入</View>
                            <View className="column-name flex1">支出</View>
                            <View className="column-name flex1">结余</View>
                        </View>
                        {months.map(item => {
                            return (
                                <View className="table-row flex-row" key={item.month}>
                                    <View className="column-val month-column">{item.name}</View>
                                    <View className="column-val flex1">{MoneyFormat(item.data.income)}</View>
                                    <View className="column-val flex1">{MoneyFormat(item.data.expense)}</View>
                                    <View className="column-val flex1">{MoneyFormat(item.data.balance)}</View>
                                </View>
                            )
                        })}
                    </View>
                </View>
            </View>
            <EditBalance show={editVisible} membersData={membersData} onClose={editClose}></EditBalance>
        </Page>
    )
}

export default Balance
